package com.ds.smartstudio.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.ds.smartstudio.entity.User;
import com.ds.smartstudio.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 检查方法是否需要过滤
        if (!(handler instanceof HandlerMethod)) return true;

        // 初步验证token
        if (StrUtil.isBlank(token)) {
            log.error("不要乱搞");
            return false;
        }
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
            User user = userService.getById(Integer.valueOf(userId));
            if (user == null) {
                log.error("不要乱搞");
                return false;
            } else {
                // 验证签证
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getDsUserPassword())).build();
                jwtVerifier.verify(token);
            }
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            log.error(e.toString());
        }

        return true;
    }
}
